package com.lagou.zk;

import com.lagou.bean.Jdbc;
import com.lagou.utils.DBCPUtil;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/*
 * @className ZkJdbc
 * @description
 * @author admin
 * @date 2022/7/8 21:58
 * */
public class ZkJdbc {
    // 路径
    private String path = "/jdbc";
    // 创建Jdbc对象
    Jdbc jdbc = new Jdbc();
    Connection conn = null;

    // 获取zkClient对象
    ZkClient zkClient = null;

    public void connectZkClient(){
        // 创建zkClient对象
        zkClient = new ZkClient("centos7-1:2181,centos7-2:2181,centos7-3:2181");
        // 设置自定义序列化类型
        zkClient.setZkSerializer(new ZkStrSerializer());
        // 设置数据库连接配置信息
        jdbc.setDriverName("com.mysql.cj.jdbc.Driver");
        jdbc.setUrl("jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8&serverTimezone=UTC");
        jdbc.setUser("root");
        jdbc.setPassword("123456");
        getConnection();
        // 如果该节点不存在则创建一个持久化节点
        boolean exists = zkClient.exists(path);
        if(!exists){
            zkClient.createPersistent(path,jdbc);
        }
        System.out.println("发布连接池配置信息到zk成功！");
        // 对/jdbc节点注册监听器，节点数据发生变化后重新获取数据库连接池
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println("zk中的数据库连接配置信息发生改变！尝试重新获取数据库连接池！");
                String infos = data.toString();
                String[] info = infos.split(" ");
                jdbc.setDriverName(info[0]);
                jdbc.setUrl(info[1]);
                jdbc.setUser(info[2]);
                jdbc.setPassword(info[3]);
                // 重新获取数据库连接池
                getConnection();
            }

            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path+" data is deleted!");
            }
        });
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    // 获取连接
    public void getConnection(){
        if(conn!=null){
            DBCPUtil.close(conn);
        }
        try {
            conn = DBCPUtil.getConnection(jdbc);
            System.out.println("Database connection succeeded,host:"+jdbc.getUrl()+"\tuser:"+jdbc.getUser());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ZkJdbc zkJdbc = new ZkJdbc();
        zkJdbc.connectZkClient();
    }
}
